﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using GestionEco;
using System.Drawing;
using System.IO;
using System.Threading;

namespace Ecosystème
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        private IntPtr drawSurface;
        float timer = 10; 
        const float TIMER = 1;

        public Game1(IntPtr drawSurface)
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            this.drawSurface = drawSurface;
            graphics.PreparingDeviceSettings += new EventHandler<PreparingDeviceSettingsEventArgs>(graphics_PreparingDeviceSettings);
            System.Windows.Forms.Control.FromHandle((this.Window.Handle)).VisibleChanged +=new EventHandler(Game1_VisibleChanged);
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            Traitements.initialisation(this.Content);

            //convertion des images en textures

            foreach (EtreVivant e in Traitements.laListeEcosysteme)
            {
                System.Drawing.Image im = e.ImageEtre;
                //On resize l'image
                Bitmap img = new Bitmap(im, new Size(100, 100));
                using (MemoryStream s = new MemoryStream())
                {

                    img.Save(s, System.Drawing.Imaging.ImageFormat.Png);
                    s.Seek(0, SeekOrigin.Begin);
                    // Ajout de l'image sur la texture de l'être vivant
                    e.Texture = Texture2D.FromStream(this.spriteBatch.GraphicsDevice, s);
                }
            }

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
            timer -= elapsed;
            // TODO: Add your update logic here

            if (timer<0)
            {
                if (Traitements.laListeEcosysteme.Count != 0)
                {
                     Traitements.actionEtreVivant();
                }
                timer = TIMER;
            }

          //  base.Update(gameTime);
            
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.White);
            int hauteur = 0;
            int largeur = 0;
            float scale = 0;
            // TODO: Add your drawing code here

            //Les cases sont dessinées
            spriteBatch.Begin();
            foreach (List<Case> C1 in Traitements.lePlateau.LesCases)
            {
                hauteur = 0;
                foreach (Case C2 in C1)
                {
                    
                    //Création des coordonnées de la case
                    scale = 50f / C2.TextureCase.Width;
                    C2.Position = new Vector2(largeur, hauteur);

                    //On dessine les cases
                    spriteBatch.Draw(C2.TextureCase, C2.Position, null, Microsoft.Xna.Framework.Color.White, 0, new Vector2(0, 0), scale, SpriteEffects.None, 0);
                    hauteur += (int)((C2.TextureCase.Height)*scale);
                }
                largeur += (int)((C1.ElementAt(0).TextureCase.Width) * scale);
            }

            spriteBatch.End();
            //Les etre vivants sont dessinés
            spriteBatch.Begin();

            int interieurCaseX = 0;
            int interieurCaseY = 0;
            List<String> dejaDessine= new List<String>();

            foreach (List<Case> C3 in Traitements.lePlateau.LesCases)
            {

                foreach (Case C4 in C3)
                {

                    foreach (EtreVivant ev in C4.ListEVCase)
                    {
                        if (dejaDessine.IndexOf(ev.GetType().ToString()) == -1)
                        {
                            spriteBatch.Draw(ev.Texture, new Vector2(C4.Position.X + interieurCaseX, C4.Position.Y + interieurCaseY), null, Microsoft.Xna.Framework.Color.White, 0, new Vector2(0, 0), scale, SpriteEffects.None, 0);
                            ev.LesCoordDeEtreVivant.Origine = new Vector2(C4.Position.X + interieurCaseX, C4.Position.Y + interieurCaseY);
                            interieurCaseX += (int)(0.08F *(ev.Texture.Width));
                            interieurCaseY += (int)(0.08F * (ev.Texture.Height));
                            dejaDessine.Add(ev.GetType().ToString());
                        }
                        else
                        {
                            ev.LesCoordDeEtreVivant.Origine = new Vector2(interieurCaseX, interieurCaseY);

                        }

                    }
                    interieurCaseX = 0;
                    interieurCaseY = 0;
                    dejaDessine.Clear();
                }

            }

            spriteBatch.End();
           
            base.Draw(gameTime);
        }

        void graphics_PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e)
        {
            e.GraphicsDeviceInformation.PresentationParameters.DeviceWindowHandle = drawSurface;
        }

        private void Game1_VisibleChanged(object sender, EventArgs e)
        {
            if (System.Windows.Forms.Control.FromHandle((this.Window.Handle)).Visible == true)
                System.Windows.Forms.Control.FromHandle((this.Window.Handle)).Visible = false;
        }
        
    }
}
